using APITransLib.Contracts;
using Microsoft.AspNetCore.Mvc;

namespace ChatWithMulitAIServer.Controllers;

[ApiController]
[Route("api/agent")]
public class AgentController : ControllerBase
{
    private static readonly Dictionary<string, AgentProfileDto> Profiles = new();

    [HttpGet("{ownerUserId}")]
    public ActionResult<AgentProfileDto> Get(string ownerUserId)
    {
        if (!Profiles.TryGetValue(ownerUserId, out var p))
        {
            p = new AgentProfileDto { OwnerUserId = ownerUserId };
            p.SocialStatus = EvaluateSocialStatus(p.ValueScore, p.HonorScore);
            Profiles[ownerUserId] = p;
        }
        return Ok(p);
    }

    [HttpPost("{ownerUserId}")]
    public ActionResult<UpdateAgentProfileResponse> Update(string ownerUserId, UpdateAgentProfileRequest req)
    {
        if (!Profiles.TryGetValue(ownerUserId, out var p))
        {
            p = new AgentProfileDto { OwnerUserId = ownerUserId };
        }
        if (req.Name is not null) p.Name = req.Name;
        if (req.Persona is not null) p.Persona = req.Persona;
        if (req.Settings is not null)
        {
            foreach (var kv in req.Settings)
                p.Settings[kv.Key] = kv.Value;
        }
        if (req.ValueScore.HasValue) p.ValueScore = req.ValueScore.Value;
        if (req.HonorScore.HasValue) p.HonorScore = req.HonorScore.Value;

        // update derived status
        p.SocialStatus = EvaluateSocialStatus(p.ValueScore, p.HonorScore);

        // simple progression per update
        p.Xp += 10;
        if (p.Xp >= p.Level * 100)
        {
            p.Level++;
            p.Xp = 0;
        }
        Profiles[ownerUserId] = p;
        return Ok(new UpdateAgentProfileResponse { Profile = p });
    }

    [HttpPost("{ownerUserId}/generate")]
    public ActionResult<AgentGenerateResponse> Generate(string ownerUserId, AgentGenerateRequest req)
    {
        var reply = $"[{ownerUserId} agent {DateTime.UtcNow:HH:mm:ss}] {req.Prompt}";
        return Ok(new AgentGenerateResponse { Reply = reply });
    }

    private static string EvaluateSocialStatus(double valueScore, double honorScore)
    {
        var total = valueScore * 0.6 + honorScore * 0.4; // weighted
        return total switch
        {
            >= 90 => "Legend",
            >= 75 => "Elite",
            >= 60 => "Respected",
            >= 40 => "Normal",
            _ => "Newbie"
        };
    }
}
